var labels = new Array();
var show_label_num = 6;
var show_limit_num = 6;
var time = new Array(0,1,0,0);
var score = 0;
var pass_num = 0;
var poll = null;
var off_limit = new Array();
var x1 = 0;
var y1 = 0;
var x2 = 0;
var y2 = 0;

$(document).ready(function() {
    $("#game_time").html(time[0] + "" + time[1] + ":" + time[2] + time[3]);
    $("#game_score").html(score);
    $("#game_pass_num").html(pass_num);
    show_first_off_limit_words();
    document.onkeydown = click_label;
    set_rest_time();
    $("#game_label").click(function() {
        label();
    });
    $("#game_pass").click(function() {
        pass();
    });
    poll = setInterval(check_background, 2000);
    $("#game_middle_image").imgAreaSelect({ handles: true, onSelectEnd: function (img, selection) {
			x1 = selection.x1;
			x2 = selection.x2;
			y1 = selection.y1;
			y2 = selection.y2;
		}
	});
});

function set_rest_time() {
    setInterval(function() {
        if (time[0] == 0 && time[1] == 0 && time[2] == 0 && time[3] == 0) {
            window.clearInterval(poll);
            self.location = "/result/" + $("#game_score").html();
        } else if (time[3] != 0) {
            time[3]--;
        } else {
            time[3] = 9;
            if (time[2] != 0) {
                time[2]--;
            } else {
                time[2] = 5;
                if (time[1] != 0) {
                    time[1]--;
                } else if (time[0] != 0) {
                    time[0]--;
                }
            }
        }
        $("#game_time").html(time[0] + "" + time[1] + ":" + time[2] + time[3]);
    }, 1000);
}

function click_label(event) {
    var e = event || window.event;
    if (e.keyCode == 13) {
        $("#game_label").click();
    }
}

function label() {
    var label_exist = false;
    if (check_off_limit($("#game_input").val())) {
        if ($("#game_input").val() != "") {
            for (var i = 0; i < labels.length; i++) {
                if (labels[i] == $("#game_input").val()) {
                    $("#game_input").val("");
                    label_exist = true;
                    return;
                }
            }
            labels.push($("#game_input").val());
            show_labels();
        }
        if ($("#game_input").val() != "" && !label_exist && !check_partial()) {
            $.get("http://127.0.0.1:8000/check_match/" + $("#game_input").val() + "/", function(data) {
                alert(data);
                var data_array = data.split("##");
                if (data_array[0] == "match") {
                    alert(data);
                    score += 100;
                    $("#game_score").html(score);
                    $("#game_middle_image").attr("src", data_array[1])
                    clear_labels();
                    clear_off_limit();
                    show_off_limit_words(data_array[2])
                    var str_width = data_array[3]
                    var width = parseInt(str_width)
                    var str_height = data_array[4]
                    var height = parseInt(str_height)
                    if (width >= height) {
                        if (width != 0 && width <= 300) {
                            $("#game_middle_image").attr('style','width:' + str_width + "px;")
                        } else {
                            $("#game_middle_image").attr('style','width:300px;')
                        }
                    } else {
                        if (height != 0 && height <= 300) {
                            $("#game_middle_image").attr('style','width:' + str_height + "px;")
                        } else {
                            $("#game_middle_image").attr('style','height:300px;')
                        }
                    }
                    $("#game_info").addClass("game-middle-success");
                    $("#game_info").html("Matched on " + $("#game_input").val() + ": " + 100 + " points");
                    $("#game_info").fadeOut(4000, function() {
                        $("#game_info").removeClass("game-middle-success");
                        $("#game_info").html("Your partner hasn't suggested any labels yet.");
                        $("#game_info").show();
                    });
                }
                $("#game_input").val("");
            });
        } else if ($("#game_input").val() != "" && !label_exist && check_partial()) {
            $.get("http://127.0.0.1:8000/check_pic/" + $("#game_input").val() + "/" + x1 + "/" + y1 + "/" + x2 + "/" + y2 + "/", function(data) {
                alert(data);
                var data_array = data.split("##");
                if (data_array[0] == "match") {
                    score += 100;
                    $("#game_score").html(score);
                    $("#game_middle_image").attr("src", data_array[1])
                    clear_labels();
                    clear_off_limit();
                    show_off_limit_words(data_array[2])
                    var str_width = data_array[3]
                    var width = parseInt(str_width)
                    var str_height = data_array[4]
                    var height = parseInt(str_height)
                    if (width >= height) {
                        if (width != 0 && width <= 300) {
//                            $("#game_middle_image").attr('style','width:' + str_width + "px;")
                            $("#game_middle_image").attr('style','width:300px;')
                        } else {
                            $("#game_middle_image").attr('style','width:300px;')
                        }
                        alert($("#game_middle_image").height());
                    } else {
                        if (height != 0 && height <= 300) {
//                            $("#game_middle_image").attr('style','width:' + str_height + "px;")
                            $("#game_middle_image").attr('style','height:300px;')
                        } else {
                            $("#game_middle_image").attr('style','height:300px;')
                        }
                    }
//                    $("#game_middle_image").imgAreaSelect({ remove: true });
                    $("#game_info").addClass("game-middle-success");
                    $("#game_info").html("Matched on " + $("#game_input").val() + ": " + 100 + " points");
                    $("#game_info").fadeOut(4000, function() {
                        $("#game_info").removeClass("game-middle-success");
                        $("#game_info").html("Your partner hasn't suggested any labels yet.");
                        $("#game_info").show();
                    });
                }
                $("#game_input").val("");
            });
        }
    } else {
        $("#game_input").val("")
    }
}

function check_partial() {
//    if (x2 ==0 || y2 == 0 || x1 == x2 || y1 == y2) {
//        return false;
//    } else {
//        return true;
//    }
    return true;
}

function clear_partial() {
    x1 = 0;
    x2 = 0;
    y1 = 0;
    y2 = 0;
}

function check_background() {
    $.get("http://127.0.0.1:8000/check_match_background/", function(data) {
        var data_info = data.split('##');
        if (data_info[0] == 'match') {
            score += 100;
            $("#game_score").html(score);
            $("#game_middle_image").attr("src", data_info[1])
            clear_labels();
            clear_off_limit();
            clear_partial();
            show_off_limit_words(data_info[2])
            var str_width = data_info[3]
            var width = parseInt(str_width)
            var str_height = data_info[4]
            var height = parseInt(str_height)
            if (width >= height) {
                if (width != 0 && width <= 300) {
                    $("#game_middle_image").attr('style','width:' + str_width + "px;")
                } else {
                    $("#game_middle_image").attr('style','width:300px;')
                }
            } else {
                if (height != 0 && height <= 300) {
                    $("#game_middle_image").attr('style','width:' + str_height + "px;")
                } else {
                    $("#game_middle_image").attr('style','height:300px;')
                }
            }
            $("#game_info").addClass("game-middle-success");
            $("#game_info").html("Matched on " + $("#game_input").val() + ": " + 100 + "points");
            $("#game_info").fadeOut(4000, function() {
                $("#game_info").removeClass("game-middle-success");
                $("#game_info").html("Your partner hasn't suggested any labels yet.");
                $("#game_info").show();
            });
        }
        if (data_info[0] == 'not_match') {
            if ($("#game_info").html().substr(0, 4) == "Your" && $("#game_info").html() != "Your partner need to pass." && $("#game_info").html() != "Wait for you partner to pass.") {
                if (data_info[1] == '0') {
                    $("#game_info").html("Your partner hasn't suggested any labels yet.");
                } else if (data_info[1] == '1') {
                    $("#game_info").html('Your partner has suggested 1 label.');
                } else {
                    $("#game_info").html('Your partner has suggested ' + data_info[1] + ' labels.');
                }
            }
        }
        if (data_info[0] == 'pass') {
            $("#game_info").removeClass("game-middle-wait-pass");
            pass_num++;
            $("#game_pass_num").html(pass_num);
            $("#game_middle_image").attr("src", data_info[1])
            clear_labels();
            clear_off_limit();
            show_off_limit_words(data_info[2])
            var str_width = data_info[3]
            var width = parseInt(str_width)
            var str_height = data_info[4]
            var height = parseInt(str_height)
            if (width >= height) {
                if (width != 0 && width <= 300) {
                    $("#game_middle_image").attr('style','width:' + str_width + "px;")
                } else {
                    $("#game_middle_image").attr('style','width:300px;')
                }
            } else {
                if (height != 0 && height <= 300) {
                    $("#game_middle_image").attr('style','width:' + str_height + "px;")
                } else {
                    $("#game_middle_image").attr('style','height:300px;')
                }
            }
            $("#game_info").addClass("game-middle-success");
            $("#game_info").html("Pass");
            $("#game_info").fadeOut(4000, function() {
                $("#game_info").removeClass("game-middle-success");
                alert($("#game_info").html());
                $("#game_info").html("Your partner hasn't suggested any labels yet.");
                $("#game_info").show();
            });
        }
        if (data_info[0] == 'not_pass') {
            $("#game_info").addClass("game-middle-wait-pass");
            $("#game_info").html("Your partner need to pass.");
        }
    });
}

function show_labels() {
    if (labels.length > show_label_num) {
        $("#label1").html(labels[labels.length - show_label_num]);
        $("#label2").html(labels[labels.length - show_label_num + 1]);
        $("#label3").html(labels[labels.length - show_label_num + 2]);
        $("#label4").html(labels[labels.length - show_label_num + 3]);
        $("#label5").html(labels[labels.length - show_label_num + 4]);
        $("#label6").html(labels[labels.length - show_label_num + 5]);
    } else {
        $("#label" + labels.length).html(labels[labels.length - 1]);
    }
}

function clear_labels() {
    labels = []
    for (var i = 1; i <= show_label_num; i++) {
        $("#label" + i).html("");
    }
}

function show_off_limit_words(off_limit_string) {
    off_limit = null;
    off_limit = new Array();
    var off_limit_list = off_limit_string.split("#");
    for (var i = 1; i <= show_limit_num; i++) {
        $("#limit" + i).html("");
    }
    for (var i = 1; i <= off_limit_list.length; i++) {
        off_limit.push(off_limit_list[i - 1]);
        $("#limit" + i).html(off_limit_list[i - 1]);
    }
}

function show_first_off_limit_words() {
    $.get("http://127.0.0.1:8000/get_first_off_limit_list/", function(data) {
        if (data != "no_off_limit") {
            var first_off_limit_list = data.split('#');
            for (var i = 1; i <= first_off_limit_list.length; i++) {
                $("#limit" + i).html(first_off_limit_list[i - 1]);
                off_limit.push(first_off_limit_list[i - 1]);
            }
        }
    });
}

function check_off_limit(keyword) {
    for (var i = 0; i < off_limit.length; i++) {
        if (off_limit[i] == keyword) {
            j = i + 1;
            $("#limit" + j).addClass("game-offlimit");
            return false;
        }
    }
    return true;
}

function clear_off_limit() {
    for (var i = 1; i <= show_limit_num; i++) {
        $("#limit" + i).removeClass("game-offlimit");
    }
}

function pass() {
    $.get("http://127.0.0.1:8000/check_pass/", function(data) {
        if (data == "finish") {
            $("#game_info").html("Wait for you partner to pass.");
            $("#game_info").addClass("game-middle-wait-pass");
        }
    });
}